package a66weding.com.jiehuntong.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.base.BaseActivity;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.pager.BasePager;
import a66weding.com.jiehuntong.pager.Tools_CreatestoryPager;

/**
 * Created by admin on 2016/5/31.
 */
public class Tools_WeddingStoryActivity extends BaseActivity implements View.OnClickListener {

    private View myBodyView;
    private TextView writeStory_tv, title_left, title_center;
    private HomeBaseFragment mFragment;
    private static Map<String, BasePager> mStoryPage;
    private Button photoBtn, cameraBtn, quxiaoBtn, publishmace_btn, confirmBtn;
    private Dialog dialog, mDialog;
    private ImageButton addcover_btn, ispublicR_btn;
    boolean Button_Flag = false;
    private LinearLayout ispublicH_ll;
    private ImageView addcover_iv;

    @Override
    protected View getContentView() {
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("Tools_WeddingStoryActivity", this);
        myBodyView = View.inflate(this, R.layout.activity_tools_weddingstory, null);

        title_left = (TextView) myBodyView.findViewById(R.id.headleft_title_tv);
        title_center = (TextView) myBodyView.findViewById(R.id.headcenter_title_tv);
        writeStory_tv = (TextView) myBodyView.findViewById(R.id.headright_title_tv);


        publishmace_btn = (Button) myBodyView.findViewById(R.id.publishmace_button);
        //监听
        writeStory_tv.setOnClickListener(this);
        publishmace_btn.setOnClickListener(this);
        return myBodyView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headright_title_tv:
                everyPager("写故事");
                break;
            case R.id.publishmace_button:
                publishStory();
                break;
            case R.id.addcover_imageview:
                CUtils.showToast("添加封面");
                break;
            case R.id.tv_ispublic:

                break;
            case R.id.button_confirm:

        }
    }

    private void CreatePage(String pagerName) {
        Intent intent = new Intent(this, Tools_WritesstoryActivity.class);
        startActivity(intent);
    }

    private void everyPager(String pagerName) {
        mStoryPage = new HashMap<String, BasePager>();
        mStoryPage.put(pagerName, new Tools_CreatestoryPager(this));
        setFragment(pagerName);
    }

    private void setFragment(String pagerName) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        mFragment = new HomeBaseFragment();
        Bundle mBundle = new Bundle();
        mBundle.putString("pagerName", pagerName);
        mFragment.setArguments(mBundle);

        transaction.replace(R.id.flay_baseactivity_content, mFragment);
        transaction.commit();

    }

    public static class HomeBaseFragment extends Fragment {

        public HomeBaseFragment() {

        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                                 @Nullable Bundle savedInstanceState) {
            String pagerName = (String) getArguments().get("pagerName");
            BasePager pager = getBasePager(pagerName);
            if (null != pager)
                return pager.mRootView;
            return null;
        }


    }

    /**
     * 根据索引位置获取指定的 BasePager 页面
     */
    public static BasePager getBasePager(String pagerName) {
        BasePager pager = mStoryPage.get(pagerName);
        if (null != pager && !pager.mInit) {
            pager.mInit = true;
            pager.initData();
        }
        return pager;
    }

    /**
     * 发表故事
     */
    private void publishStory() {

        mDialog = new Dialog(this, R.style.myDialogTheme);
        View view = View.inflate(this, R.layout.activity_tools_dialog_publish, null);
        mDialog.setContentView(view);
        addcover_iv = (ImageView) view.findViewById(R.id.dialogpub_addcover_imageview);
        ispublicH_ll = (LinearLayout) view.findViewById(R.id.dialogpub_ll_red_ispublic);
        ispublicR_btn = (ImageButton) view.findViewById(R.id.dialogpub_btn_red_ispublic);
        confirmBtn = (Button) view.findViewById(R.id.dialogpub_button_confirm);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CUtils.showToast("确定");
                CreatePage("确定");
                //传入数据到服务器
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        addcover_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CUtils.showToast("添加封面");
                showDialog();
            }
        });

        ispublicH_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Button_Flag) {
                    ispublicR_btn.setBackgroundResource(R.mipmap.storyshoucang);
                    Button_Flag = false;
                } else {
                    ispublicR_btn.setBackgroundResource(R.mipmap.shoucanghui);
                    Button_Flag = true;
                }
            }
        });

        Window dialogWindow = mDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER | Gravity.CENTER);
        dialogWindow.setAttributes(lp);
        mDialog.show();
    }

    /**
     * Dialog设置封面
     */

    private void showDialog() {
        View view = getLayoutInflater().inflate(R.layout.activity_tools_dialog_photo, null);
        photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);
        cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);
        quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);

        photoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPhoto();
                dialog.dismiss();
            }
        });
        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCamera();
                dialog.dismiss();
            }
        });
        quxiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 为弹出窗口实现监听类
     */

    /**
     * 调用系统相册
     */
    private void showPhoto() {

        Intent intent = new Intent(Intent.ACTION_PICK, null);
        /**
         * 下面这句话，与其它方式写是一样的效果，如果：
         * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
         * intent.setType(""image/*");设置数据类型
         * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
         *
         */
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 1);
    }

    /**
     * 拍照
     */
    private void showCamera() {
        /**
         * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
         * 文档，you_sdk_path/docs/guide/topics/media/camera.html
         *
         */
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //下面这句指定调用相机拍照后的照片存储的路径
        File imgFile =new File(FileUtil.getImgFile(this),"gushi.jpg") ;
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
        startActivityForResult(intent, 2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 如果是直接从相册获取
            case 1:
                startPhotoZoom(data.getData());
                break;
            // 如果是调用相机拍照时
            case 2:
                File temp = new File(Environment.getExternalStorageDirectory() + "/xiaoma.jpg");
                startPhotoZoom(Uri.fromFile(temp));
                break;
            // 取得裁剪后的图片
            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 */
                if (data != null) {
                    setPicToView(data);
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            /**
             * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上
             * 传到服务器，QQ头像上传采用的方法跟这个类似
             */
            addcover_iv.setBackgroundDrawable(drawable);
        }
    }
}